package com.tim.app.db.dao;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.SQLException;
import android.text.TextUtils;

import com.application.library.log.DLOG;


public abstract class AbstractDAO {

    protected String TAG;
    protected Context mContext;
    protected DBHelper mDB;
    boolean writeOpen = false;

    public AbstractDAO(Context context) {
        mContext = context;
        mDB = new DBHelper(context);
        TAG = this.getClass().getSimpleName();
    }

    public Cursor query(String sql) {
        return mDB.rawQuery(sql, null);
    }

    public Cursor query(String sql, String[] selectionArgs) {
        return mDB.rawQuery(sql, selectionArgs);
    }

    public long insert(String table, String nullColumnHack, ContentValues cv) {
        return mDB.insert(table, nullColumnHack, cv);
    }

    public long update(String table, ContentValues cv, String whereClause,
                       String[] whereArgs) {
        synchronized (mDB) {
            return mDB.update(table, cv, whereClause, whereArgs);
        }
    }

    public boolean delete(String table, String whereClause, String[] whereArgs) {
        return mDB.delete(table, whereClause, whereArgs);
    }

    public void openWritableDB() throws DaoException {
        try {
            mDB.openWritable();
            writeOpen = true;
        } catch (SQLException e) {
            throw new DaoException(e);
        }
    }

    public void openReadableDB() throws DaoException {
        try {
            mDB.openReadable();
            writeOpen = false;
        } catch (SQLException e) {
            throw new DaoException(e);
        }
    }

    public synchronized void clearData() {

        String tableName = getTableName();

        if (TextUtils.isEmpty(tableName))
            return;
        try {
            openWritableDB();
            delete(tableName, null, null);
        } catch (DaoException e) {
            DLOG.d(TAG, e.getMessage());
        } finally {

            closeDB();
        }
    }

    abstract String getTableName();

    public void closeDB() {
        synchronized (DBHelper.class) {
            if (mDB != null)
                mDB.close();
        }
    }

    public void execSql(String sql){
        synchronized (mDB) {
           mDB.execSql(sql);
        }
    }
    public Context getContext() {
        return mContext;
    }

    protected boolean checkCursorAvaible(Cursor cursor) {

        if (cursor != null && cursor.getCount() > 0 && !cursor.isClosed()) {
            return true;
        }

        return false;

    }

    public class DaoException extends Exception {
        private static final long serialVersionUID = 2440991940165208939L;

        public DaoException(Throwable e) {
            super(e);
        }

        public DaoException(String message, Throwable e) {
            super(message, e);
        }
    }
}
